<template>
	<div>
		<el-button v-if="showUpButton" type="success" icon="ele-Plus" @click="()=>{ dialogVisible=true }">上传文件
		</el-button>
		<el-table :data="tableData" v-loading="listLoading" style="width: 100%" :show-header="false">
			<el-table-column prop="fileName" label="文件名" />
			<el-table-column width="150" label="操作">
				<template #default="scope">
					<el-button type="primary" link @click="downloadFile(scope.row.id)">下载</el-button>
					<el-button v-if="showUpButton" type="primary" link @click="deleteHandle(scope.row.id)">删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-dialog title="文件导入" v-model="dialogVisible" width="40%" class="customDialog">
			<el-upload class="upload-demo" ref="uploadRef" :file-list="fileList" :limit="10" multiple action="#"
				:before-upload="beforeupload" :on-exceed="handleExceed" :on-success="handleSuccess"
				:on-error="handleError" :http-request="uploadFile" :with-credentials='true'>
				<template #trigger>
					<el-button type="primary">选取文件</el-button>
				</template>
			</el-upload>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose">取消</el-button>
					<el-button type="primary" @click="submitUpload">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { reactive, toRefs, onBeforeMount, ref, nextTick, watch, defineComponent } from 'vue'
import { ElMessage, UploadInstance, ElLoading, ElMessageBox } from 'element-plus'
import type {UploadRequestOptions, UploadFile} from 'element-plus'
import { fileApi } from '/@/api/fileapi'
export default defineComponent({
	name: 'fileUpload',
	props: {
		businessId: {
			type: String,
			default: () => ''
		},
		showUpButton: {
			type: Boolean,
			default: true
		}
	},
	setup(props, ctx) {
		const uploadRef = ref<UploadInstance>()
		const state = reactive({
			fileList: [],
			tableData: [],
			listLoading: false,
			dialogVisible: false
		}) 
		// 页面加载时
		onBeforeMount(() => {
			loadList()
		})
		const beforeupload = (file: any) => {
			return true
		}
		const handleExceed =  (files: any, fileList: any) => {
			ElMessage.error('一次只能导入10个文件！')
		}
		const handleSuccess = (response: any, file: any, fileList: any) => {
			// console.log(response.code)
			if (response.code === 0) {
				ElMessage.success('上传成功！')
			} else {
				ElMessage.error('上传失败！')
			}
		}
		const handleError = (err: any, file: any, fileList: any) => {
			ElMessage.error('上传失败！')
		}
		const uploadFile = (options: UploadRequestOptions) => {
			// none
		}
		const dowloadFile = (uploadFile: UploadFile) => {
			var a = document.createElement("a");
			a.href = import.meta.env.VITE_API_URL + fileApi().serverContextPath + "/file/downloadFile/" + uploadFile.url
			a.click();
		}
		const deleteFile = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
			fileApi().delete(uploadFile.url)
		}
		const downloadFile  = (id: any) => {
			fileApi().downloadFile(id);
		}
		// 删除
		const deleteHandle = (id: string | undefined) => {
			ElMessageBox.confirm('是否确定删除', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				var ids = id ? [id] : ''
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				fileApi().delete(ids).then((data) => {
					if (data && data.code === 0) {
						ElMessage.success('删除成功！')
						loadList()
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error('删除失败！')
				}).finally(() => {
					loading.close()
				})
			})
		}
		//查询
		const loadList = () => {
			state.listLoading = true
			fileApi().getFileListByBusId(props.businessId).then(data => {
				if (data && data.code === 0) {
					state.tableData = data.fmLIst
				} else {
					state.tableData = []
				}
			}).catch(() => {
			}).finally(() => {
				state.listLoading = false
			})
		}
		//取消修改
		const handleClose = () => {
			state.dialogVisible = false
			uploadRef.value!.clearFiles()
			state.fileList = []
			loadList()
		}
		//上传文件
		const submitUpload = () => {
			let formData = new FormData()
			nextTick(() => {
				state.fileList.forEach((val, index) => {
					formData.append('file', val.raw)
				})
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				formData.append('businessId', props.businessId)
				fileApi().uploadFile(formData).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('上传成功！')
						handleClose()
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error('上传失败！')
				}).finally(() => {
					loading.close()
				})
			})
			
		}
		watch( () => props.businessId, (val: string) => {
			if (val) {
				loadList()
			}
		})
		return {
			uploadRef,
			beforeupload,
			handleExceed,
			handleSuccess,
			handleError,
			uploadFile,
			dowloadFile,
			deleteFile,
			downloadFile,
			deleteHandle,
			handleClose,
			submitUpload,
			...toRefs(state),
		}
	}
})
</script>